package com.restaurant.validators;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.restaurant.domain.Employeecredential;
import com.restaurant.service.EmployeecredentialService;

public class LoginFormValidator implements Validator{

	@Autowired
	private EmployeecredentialService objEmployeecredentialService;
	
	@Override
	public boolean supports(Class<?> arg0) {
		return Employeecredential.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object arg0, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "login.error");
		
		Employeecredential employeecredential = (Employeecredential)arg0;
		
		if(employeecredential.getUsername()!="" && employeecredential.getPassword()!=""){
			String query = "SELECT e FROM Employeecredential AS e WHERE e.username = \'"+ employeecredential.getUsername() + "\' AND e.password = \'" + employeecredential.getPassword() + "\'";
			List<Employeecredential> listEmployeecredentials = null;
			try {
				listEmployeecredentials = objEmployeecredentialService.loadByHql(query);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(listEmployeecredentials.size() <= 0)
				//errors.reject("username", "login.error");
				ValidationUtils.rejectIfEmpty(errors, "username", "login.error");
		}
	}
	
}
